{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第一种方法\n",
      "200\n",
      "152801\n",
      "第二种方法\n",
      "200\n",
      "153210\n",
      "第三种方法\n",
      "200\n",
      "153003\n",
      "<CookieJar[<Cookie BAIDUID=1E5C0796FE639D69D1FA99ED0520D76D:FG=1 for .baidu.com/>, <Cookie BIDUPSID=1E5C0796FE639D69D1FA99ED0520D76D for .baidu.com/>, <Cookie H_PS_PSSID=1468_21109_26350_28518_28415_22157 for .baidu.com/>, <Cookie PSTM=1551268730 for .baidu.com/>, <Cookie delPer=0 for .baidu.com/>, <Cookie BDSVRTM=0 for www.baidu.com/>, <Cookie BD_HOME=0 for www.baidu.com/>]>\n"
     ]
    }
   ],
   "source": [
    "#! /usr/bin/python\n",
    "# -*- coding:UTF-8 -*-\n",
    "\n",
    "import cookielib\n",
    "import urllib2\n",
    "\n",
    "url = 'http://www.baidu.com'\n",
    "response1 = urllib2.urlopen(url)\n",
    "\n",
    "print \"第一种方法\"\n",
    "#获取状态码，200表示成功\n",
    "print response1.getcode()\n",
    "#获取网页内容的长度\n",
    "print len(response1.read())\n",
    "\n",
    "#获取网页内容的长度\n",
    "print \"第二种方法\"\n",
    "request = urllib2.Request(url)\n",
    "#模拟Mozilla浏览器进行爬虫\n",
    "request.add_header(\"user-agent\",\"Mozilla/5.0\")\n",
    "response2 = urllib2.urlopen(request)\n",
    "print response2.getcode()\n",
    "print len(response2.read())\n",
    "\n",
    "print \"第三种方法\"\n",
    "cookie = cookielib.CookieJar()\n",
    "#加入urllib2处理cookie的能力\n",
    "opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))\n",
    "urllib2.install_opener(opener)\n",
    "response3 = urllib2.urlopen(url)\n",
    "print response3.getcode()\n",
    "print len(response3.read())\n",
    "print cookie"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
